<?php

class teacher extends IgnitedRecord
{
	var $has_and_belongs_to_many = 'subjects';
	var $has_many = 'grades';
	var $belongs_to = 'login';
	var $has_one = 'masters';
	
	function teacher()
	{
        parent::IgnitedRecord();
    }
    
    function update($_POST, $id)
    {
        $this->db->where('id', $id);

        $val['firstname'] = $_POST['firstname'];
        $val['secondname'] = $_POST['secondname'];
        $val['telephone'] = $_POST['telephone'];
        $val['email'] = $_POST['email'];
        $this->db->update('teachers', $val);
        
        $this->db->where('teacher_id', $id);
        $this->db->delete('subjects_teachers');
        
        foreach (explode(';', $_POST['classes_id']) as $clid):
            if (strlen($clid) > 0):
                $this->db->insert('subjects_teachers', array(   'teacher_id' => $id,
                                                                'subject_id' => $_POST['subject_id'],
                                                                'classe_id' => $clid));
            endif;
        endforeach;
        
        $this->db->where('teacher_id', $id);
        $this->db->delete('masters');
        $this->db->insert('masters', array('teacher_id' => $id, 'classe_id' => $_POST['classe_id']));  
    }
    
    function get_related($id)
    {
        $this->db->where('teacher_id', $id);
        foreach ($this->db->get('masters')->result() as $row):
            $related['classe_id'] = $row->classe_id;
        endforeach;
        if (isset($related['classe_id'])):
            $this->db->where('id', $related['classe_id']);
            foreach ($this->db->get('classes')->result() as $row):
                $related['classe'] = $row->name;
            endforeach;
        else:
            $related['classe_id'] = $related['classe'] = '';
        endif;
                        
        $this->db->where('teacher_id', $id);
        foreach ($this->db->get('subjects_teachers')->result() as $row):
            $related['subject_id'] = $row->subject_id;
            $classes_id[] = $row->classe_id;
        endforeach;
        $related['classes_id'] = $classes_id;
        
        $this->db->where('id', $related['subject_id']);
        foreach ($this->db->get('subjects')->result() as $row):
            $related['subject'] = $row->name;
        endforeach;
        
        foreach ($classes_id as $cid):
            $this->db->where('id', $cid);
            foreach ($this->db->get('classes')->result() as $row):
                $classes[] = $row->name;
            endforeach;
        endforeach;
        $related['classes'] = $classes;
        
        return $related;
    }
}
?>
